<?php
declare (strict_types=1);

namespace app\common\model;

use Exception;
use think\Collection;

class Merchant extends CommonBase
{
    public function getUserByPhoneNumber(string $phoneNumber)
    {
        if (empty($phoneNumber)) {
            return false;
        }

        $where = ['cellphone' => trim($phoneNumber), 'is_delete' => config('status.mysql.table_normal')];
        return $this->where($where)->find();
    }

    public function findUser(array $where, array $whereOr = [])
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        if (empty($whereOr)) {
            return $this->where($where)->find();
        }

        return $this->where($where)->whereOr($whereOr)->find();
    }

    public function getMerchantList(int $page = 1, int $limit = 10, array $where = []): Collection
    {
        $offset             = ($page - 1) * $limit;
        $where['is_delete'] = config('status.mysql.table_normal');
        return $this->where($where)->limit($offset, $limit)->select();
    }

    public function getMerchantCount(array $where = []): int
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        return $this->where($where)->count();
    }

    public function findMerchantById(int $id)
    {
        return $this->where(["id" => $id, 'is_delete' => config('status.mysql.table_normal')])->find();
    }

    /**
     * @throws Exception
     */
    public function addMerchant(array $data, string $roleId): bool
    {
        $data['password']              = md5($data['password']);
        $merchantRoleRelationTableName = 'merchant_role_relation';
        $merchantId                    = 0;
        try {
            $this->startTrans();
            $merchantOne = $this->where(['is_delete' => config('status.mysql.table_delete'), 'cellphone' => $data['cellphone']])->find();
            if (!empty($merchantOne)) {
                $merchant = $merchantOne->toArray();
                $this->where(['id' => $merchant['id']])->save([
                    'password'   => $data['password'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                    'is_delete'  => config('status.mysql.table_normal')]);
                $merchantId = $merchant['id'];
            } else {
                $this->save($data);
                $merchantId = $this->getLastInsID();
            }

            $roleIds = explode(',', $roleId);
            foreach ($roleIds as $roleId) {
                $obj = $this->name($merchantRoleRelationTableName)->where(['merchant_id' => $merchantId, 'role_id' => $roleId])->find();

                if (!empty($obj)) {
                    $row = $obj->toArray();
                    $this->name($merchantRoleRelationTableName)->where(['id' => $row['id']])->update([
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                        'is_delete'  => config('status.mysql.table_normal')]);
                    continue;
                }

                $this->name($merchantRoleRelationTableName)->insert([
                    'role_id'     => $roleId,
                    'merchant_id' => $merchantId,
                    'created_at'  => date('Y-m-d H:i:s'),
                    'updated_at'  => date('Y-m-d H:i:s'),
                    'is_delete'   => config('status.mysql.table_normal')]);
            }

            $this->commit();
            return true;
        } catch (Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @throws Exception
     */
    public function updateMerchant(int $id, array $data, string $roleId = ''): bool
    {
        $merchantRoleRelationTableName = 'merchant_role_relation';
        try {
            $this->startTrans();
            $data['updated_at'] = date('Y-m-d H:i:s');
            $this->where(['id' => $id])->save($data);

            if (!empty($roleId)) {
                $this->name($merchantRoleRelationTableName)->where(['merchant_id' => $id])->save(['is_delete' => config('status.mysql.table_delete')]);
                $roleIds = explode(',', $roleId);
                foreach ($roleIds as $roleId) {
                    $obj = $this->name($merchantRoleRelationTableName)->where(['merchant_id' => $id, 'role_id' => $roleId])->find();
                    if (!empty($obj)) {
                        $row = $obj->toArray();
                        $this->name($merchantRoleRelationTableName)->where(['id' => $row['id']])->update([
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s'),
                            'is_delete'  => config('status.mysql.table_normal')]);
                        continue;
                    }

                    $this->name($merchantRoleRelationTableName)->insert([
                        'role_id'     => $roleId,
                        'merchant_id' => $id,
                        'created_at'  => date('Y-m-d H:i:s'),
                        'updated_at'  => date('Y-m-d H:i:s'),
                        'is_delete'   => config('status.mysql.table_normal')]);
                }
            }

            $this->commit();
            return true;
        } catch (Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @throws Exception
     */
    public function deleteMerchant(int $id): bool
    {
        $merchantRoleRelationTableName = 'merchant_role_relation';
        try {
            $this->startTrans();
            $this->where(['id' => $id])->save(['is_delete' => config('status.mysql.table_delete')]);
            $this->name($merchantRoleRelationTableName)->where(['merchant_id' => $id])->save(['is_delete' => config('status.mysql.table_delete')]);
            $this->commit();
            return true;
        } catch (Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }
}
